# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.mysql',
#         'NAME': 'search',
#         'USER': 'root',
#         'PASSWORD': 'Huangzhe.2',
#         'HOST': 'hk.lesely.gq',
#         # 'HOST': '192.168.101.4',
#         'PORT': 3306
#     }
# }

# sqlacodegen --tables question 'mysql+pymysql://hk.lesely.tk:Huangzhe.2@root:3306/search' >tmp.py

# sqlacodegen --outfile ./server-side/models.py 'mysql+pymysql://root:Huangzhe.2@192.168.101.4:3306/restaurant'
# sqlacodegen --outfile models.py 'mysql+pymysql://hk.lesely.tk:Huangzhe.2@root:3306/search'

from flask import Flask,request
# from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from git.repo import Repo
import shutil
import threading
import os
import sys
import json
import time
import models, config, snowflake_server
from Alchemy_Class_To_JSON import Alchemy_Class_To_JSON

import get_datetime

app = Flask(__name__)
# app.config.from_object(config)
# db = SQLAlchemy(app)

engine = create_engine(config.DB_URI)
# Session = sessionmaker(bind=engine)
# session = Session()

# class Article(db.Model):
#     __tablename__ = 'article'
#     id = db.Column(db.Integer,primary_key=True,autoincrement=True)
#     title =db.Column(db.String(100),nullable=False)
#     content = db.Column(db.Text,nullable=False)

# db.create_all()

# restaurant1 = models.RestaurantInformation(rname="南京灌汤包", raddress="临淄区桓公路xx号", rtel="123456789")
# db.session.add(restaurant1)
# db.session.commit()


models.metadata.create_all(engine)

snowflake_server.run()

@app.route('/')
def hello_world():
    return 'Hello World!'

########################################################
#                                                      #
#                   查询数据库API                       #
#                                                      #
########################################################

# 根据店铺name字段或id字段查询店铺信息
@app.route('/api/consult/restautant_information')
def restautant_information():
    name = request.values.get('name', None)
    id = request.values.get('id', None)
    if name or id:
        Session = sessionmaker(bind=engine)
        session = Session()
        try:
            restrautant = session.query(models.RestaurantInformation).filter(models.RestaurantInformation.name==name).all()
            if not (restrautant and len(restrautant) > 0):
                restrautant = session.query(models.RestaurantInformation).filter(models.RestaurantInformation.id==int(id)).all()
            session.commit()
            resu = {'code':1, 'result':[], 'status':'success'}
            for each in restrautant:
                resu['result'].append(json.loads(Alchemy_Class_To_JSON(each)))
        except:
            resu = {'code':-2, 'status':'No result'}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)

# 根据店铺id字段查询分类列表
@app.route('/api/consult/menu_type')
def menu_type():
    rid = request.args.get('id', None)
    if rid:
        Session = sessionmaker(bind=engine)
        session = Session()
        # restrautant = models.RestaurantInformation.query.filter(rname=name)
        try:
            restrautant = session.query(models.RestaurantInformation).filter(models.RestaurantInformation.id==int(rid)).first()
            menutype = session.query(models.MenuType).filter(models.MenuType.position==restrautant.id).all()
            session.commit()
            resu = {'code':1, 'result':[], 'status':'success'}
            for each in menutype:
                resu['result'].append(json.loads(Alchemy_Class_To_JSON(each)))
        except:
            resu = {'code':-2, 'status':'No result'}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)

# 根据分类id字段查询商品信息
@app.route('/api/consult/goods')
def menu_goods():
    tid = request.args.get('id', None)
    if tid:
        Session = sessionmaker(bind=engine)
        session = Session()
        # restrautant = models.RestaurantInformation.query.filter(rname=name)
        try:
            menutype = session.query(models.MenuType).filter(models.MenuType.id==int(tid)).first()
            goods = session.query(models.MenuGood).filter(models.MenuGood.position==menutype.id).all()
            session.commit()
            resu = {'code':1, 'result':[], 'status':'success'}
            for each in goods:
                resu['result'].append(json.loads(Alchemy_Class_To_JSON(each)))
        except:
            resu = {'code':-2, 'status':'No result'}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)

# 根据订单号/用户/餐厅ID进行查询
@app.route('/api/consult/order')
def consult_order():
    oid = request.args.get('id', None)
    uid = request.args.get('user', None)
    rid = request.args.get('rest', None)
    Session = sessionmaker(bind=engine)
    session = Session()
    if oid:
        try:
            order = session.query(models.Order).filter(models.Order.id==int(oid)).first()
            resu = {'code':1, 'result':json.loads(Alchemy_Class_To_JSON(order, fk=True)), 'status':'success'}
        except:
            resu = {'code':-2, 'status':'No result'}
    elif uid:
        try:
            orders = session.query(models.Order).filter(models.Order.user==int(uid))
            resu = {'code':1, 'result':[], 'status':'success'}
            for each in orders:
                resu['result'].append(json.loads(Alchemy_Class_To_JSON(each)))
        except:
            resu = {'code':-2, 'status':'No result'}
    elif rid:
        try:
            orders = session.query(models.Order).filter(models.Order.position==int(rid))
            resu = {'code':1, 'result':[], 'status':'success'}
            for each in orders:
                resu['result'].append(json.loads(Alchemy_Class_To_JSON(each)))
        except:
            resu = {'code':-2, 'status':'No result'}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)

# 根据用户id/手机号查询
@app.route('/api/consult/user')
def consult_user():
    uid = request.args.get('id', None)
    utel = request.args.get('tel', None)
    Session = sessionmaker(bind=engine)
    session = Session()
    if uid:
        try:
            user = session.query(models.Order).filter(models.User.id==int(uid)).first()
            resu = {'code':1, 'result':json.loads(Alchemy_Class_To_JSON(user, fk=True)), 'status':'success'}
        except:
            resu = {'code':-2, 'status':'No result'}
    elif utel:
        try:
            user = session.query(models.Order).filter(models.User.tel==utel).first()
            resu = {'code':1, 'result':json.loads(Alchemy_Class_To_JSON(user, fk=True)), 'status':'success'}
        except:
            resu = {'code':-2, 'status':'No result'}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)

########################################################
#                                                      #
#                   新增数据库API                       #
#                                                      #
########################################################

# 新增餐厅信息
# /api/add/restaurant?name=南京大排档
@app.route('/api/add/restaurant')
def add_restaurant():
    name = request.values.get('name', None)
    address = request.values.get('address', None)
    tel = request.values.get('tel', None)
    description = request.values.get('description', None)
    business_time = request.values.get('business_time', None)
    Session = sessionmaker(bind=engine)
    session = Session()
    if name:
        # 暂时只允许注册一加店铺
        if len(session.query(models.RestaurantInformation).all()) > 0:
            resu = {'code':-3,'status':'A restaurant exists, add faild'}
        else:
            try:
                aRestaurant = models.RestaurantInformation(name=name, address=address, tel=tel, description=description, business_time=business_time)
                session.add(aRestaurant)
                session.commit()
                resu = {"code":1, "result":json.loads(Alchemy_Class_To_JSON(aRestaurant)), "status":"success"}
            except Exception as e:
                resu = {"code":-4, "status":str(e)}
    else:
        resu = {'code':-1, 'status':'Missing parameters'}
    return json.dumps(resu, ensure_ascii=False)
            
# 将首次下单的用户注册为User
def add_userRegister(name, tel):
    Session = sessionmaker(bind=engine)
    session = Session()
    try:
        if name and tel and len(session.query(models.User).filter(tel=tel).all()):
            aUser = models.User(name=name, tel=tel, register_time=get_datetime.now(), admin_status=0)
            session.add(aUser)
            session.commit()
            return {"code":1, "result":json.loads(Alchemy_Class_To_JSON(aUser)), "status":"success"}
        else:
            return {"code":-5, "status":"register faild. Missing parameters or telphone number had been used."}
    except Exception as e:
        return {"code":-4, "status":str(e)}

# 新增商品类别 （POST）
# /api/add/menu_type?name=xx&positon=1
@app.route('/api/add/menu_type')
def add_menu_type():
    name = request.values.get('name', None)
    position = request.values.get('position', None)
    Session = sessionmaker(bind=engine)
    session = Session()
    try:
        if session.query(models.MenuType).filter(models.MenuType.name==name, models.MenuType.position==int(position)).count() > 0:
            resu = {"code":2, "result":json.loads(Alchemy_Class_To_JSON(session.query(models.MenuType).filter(models.MenuType.name==name, models.MenuType.position==int(position)).first(),fk=True)),"status":"%s type has existed"%name}
        else:
            aMenutype = models.MenuType(name=name, position=int(position))
            session.add(aMenutype)
            session.commit()
            # session.query(models.MenuType).filter(models.MenuType.name==name, models.MenuType.position==int(position)).all()[-1]
            resu = {"code":1, "result":json.loads(Alchemy_Class_To_JSON(aMenutype, fk=True)), "status":"success"}
    except Exception as e:
        resu = {"code":-4, "status":str(e)}
    return json.dumps(resu, ensure_ascii=False)

# 新增商品 （将改为POST请求）
# /api/add/goods
@app.route('/api/add/goods')
def add_goods():
    name = request.values.get('name', None)
    position = request.values.get('position', None)
    price = request.values.get('price', 0.01)
    cushion = request.values.get('cushion', 0)
    offers = request.values.get('offers', None)
    parcel = request.values.get('parcel', 1.00)
    description = request.values.get('description', None)
    sale_status = request.values.get('sale_status', 0)
    picture = request.values.get('picture', None)
    Session = sessionmaker(bind=engine)
    session = Session()
    try:
        aGoods = models.Goods(name=name, position=int(position), price=float(price), cushion=int(cushion), offers=offers, parcel=float(parcel), description=description, sale_status=int(sale_status), picture=picture)
        session.add(aGoods)
        session.commit()
        resu = {"code":1, "result":json.loads(Alchemy_Class_To_JSON(aGoods)), "status":"success"}
    except Exception as e:
        resu = {"code":-4, "status":str(e)}
    return json,dumps(resu, ensure_ascii=False)


# 新增订单 （POST）
@app.route('/api/add/order')
def add_order():
    pass

# Session = sessionmaker(bind=engine)
# session = Session()

# types = session.query(models.MenuType).filter(models.MenuType.position==1).all()

# print(type(types), types)

# @app.route('/api/add/order/<user>', methods=['POST'])
# def snowflake_test(user=None):
#     if user:
#         try:
#             goods = request.form.get('goods')
#             note = request.form.get('note')
#             reservationTime = request.form.get('rTime')
#             # goods = [{"goods_id":1, "goods_num":1, "parcel_statu":1}] 注意一定使用双引号
#             goods = json.loads(goods)
#             Session = sessionmaker(bind=engine)
#             session = Session()
#             for each in goods:
#                 each["goods_info"] = Alchemy_Class_To_JSON(session.query(models.MenuGood).get(models.MenuGood.id==int(each["goods_id"])))
#         except:
#             pass
#     return {}

if __name__ == '__main__':
    app.run()
    

# @app.route('/api/restautant_information/<name>')
# def restautant_information(name=None):
#     if name:
#         restrautant = models.RestaurantInformation.objects.filter(rname=name)
#         if restrautant.exists():
#             resu = {'code':1, 'result':[], 'msg':'success'}
#             for each in restrautant:
#                 resu['result'].append(each.__dict__)
#     return json.dumps(resu,ensure_ascii=False)